package org.znxs.comfriend.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class FollowManager {

    // 单例实例
    private static FollowManager instance;

    // SharedPreferences 的键
    private static final String PREFS_NAME = "GlobalListPrefs";
    private static final String LIST_KEY = "global_list";

    // Context 对象
    private Context context;

    // 私有构造函数，防止外部实例化
    private FollowManager(Context context) {
        this.context = context.getApplicationContext();
    }

    // 获取单例实例
    public static synchronized FollowManager getInstance(Context context) {
        if (instance == null) {
            instance = new FollowManager(context);
        }
        return instance;
    }

    // 保存 List 到 SharedPreferences
    public void saveList(List<String> list) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        // 使用 Gson 将 List 转换为 JSON 字符串
        Gson gson = new Gson();
        String json = gson.toJson(list);

        editor.putString(LIST_KEY, json);
        editor.apply();
    }

    // 从 SharedPreferences 中读取 List
    public List<String> getList() {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String json = sharedPreferences.getString(LIST_KEY, null);

        // 如果存在 JSON 数据，则解析为 List
        if (json != null) {
            Gson gson = new Gson();
            Type type = new TypeToken<List<String>>() {
            }.getType();
            return gson.fromJson(json, type);
        } else {
            // 如果没有数据，返回空的 List
            return new ArrayList<>();
        }
    }

    // 添加单个元素到 List 并保存
    public void addItem(String item) {
        List<String> list = getList();
        list.add(item);
        saveList(list);
    }

    // 删除指定元素并保存
    public void removeItem(String item) {
        List<String> list = getList();
        list.remove(item);
        saveList(list);
    }

    // 清空 List 并保存
    public void clearList() {
        saveList(new ArrayList<>());
    }

    public boolean isFollowing(String userId) {
        if (userId.isBlank()) {
            return false;
        }
        return getList().contains(userId);
    }
}